/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Services;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entity.Owner;
import Entity.Person;
import Entity.Veterinarian;
import Services.exceptions.IllegalOrphanException;
import Services.exceptions.NonexistentEntityException;
import Services.exceptions.PreexistingEntityException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author itachiu
 */
public class PersonJpaController implements Serializable {

    public PersonJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Person person) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Owner owner = person.getOwner();
            if (owner != null) {
                owner = em.getReference(owner.getClass(), owner.getPersonPersonId());
                person.setOwner(owner);
            }
            Veterinarian veterinarian = person.getVeterinarian();
            if (veterinarian != null) {
                veterinarian = em.getReference(veterinarian.getClass(), veterinarian.getPersonPersonId());
                person.setVeterinarian(veterinarian);
            }
            em.persist(person);
            if (owner != null) {
                Person oldPersonOfOwner = owner.getPerson();
                if (oldPersonOfOwner != null) {
                    oldPersonOfOwner.setOwner(null);
                    oldPersonOfOwner = em.merge(oldPersonOfOwner);
                }
                owner.setPerson(person);
                owner = em.merge(owner);
            }
            if (veterinarian != null) {
                Person oldPersonOfVeterinarian = veterinarian.getPerson();
                if (oldPersonOfVeterinarian != null) {
                    oldPersonOfVeterinarian.setVeterinarian(null);
                    oldPersonOfVeterinarian = em.merge(oldPersonOfVeterinarian);
                }
                veterinarian.setPerson(person);
                veterinarian = em.merge(veterinarian);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findPerson(person.getPersonId()) != null) {
                throw new PreexistingEntityException("Person " + person + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Person person) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Person persistentPerson = em.find(Person.class, person.getPersonId());
            Owner ownerOld = persistentPerson.getOwner();
            Owner ownerNew = person.getOwner();
            Veterinarian veterinarianOld = persistentPerson.getVeterinarian();
            Veterinarian veterinarianNew = person.getVeterinarian();
            List<String> illegalOrphanMessages = null;
            if (ownerOld != null && !ownerOld.equals(ownerNew)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain Owner " + ownerOld + " since its person field is not nullable.");
            }
            if (veterinarianOld != null && !veterinarianOld.equals(veterinarianNew)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain Veterinarian " + veterinarianOld + " since its person field is not nullable.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (ownerNew != null) {
                ownerNew = em.getReference(ownerNew.getClass(), ownerNew.getPersonPersonId());
                person.setOwner(ownerNew);
            }
            if (veterinarianNew != null) {
                veterinarianNew = em.getReference(veterinarianNew.getClass(), veterinarianNew.getPersonPersonId());
                person.setVeterinarian(veterinarianNew);
            }
            person = em.merge(person);
            if (ownerNew != null && !ownerNew.equals(ownerOld)) {
                Person oldPersonOfOwner = ownerNew.getPerson();
                if (oldPersonOfOwner != null) {
                    oldPersonOfOwner.setOwner(null);
                    oldPersonOfOwner = em.merge(oldPersonOfOwner);
                }
                ownerNew.setPerson(person);
                ownerNew = em.merge(ownerNew);
            }
            if (veterinarianNew != null && !veterinarianNew.equals(veterinarianOld)) {
                Person oldPersonOfVeterinarian = veterinarianNew.getPerson();
                if (oldPersonOfVeterinarian != null) {
                    oldPersonOfVeterinarian.setVeterinarian(null);
                    oldPersonOfVeterinarian = em.merge(oldPersonOfVeterinarian);
                }
                veterinarianNew.setPerson(person);
                veterinarianNew = em.merge(veterinarianNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = person.getPersonId();
                if (findPerson(id) == null) {
                    throw new NonexistentEntityException("The person with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Person person;
            try {
                person = em.getReference(Person.class, id);
                person.getPersonId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The person with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Owner ownerOrphanCheck = person.getOwner();
            if (ownerOrphanCheck != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Person (" + person + ") cannot be destroyed since the Owner " + ownerOrphanCheck + " in its owner field has a non-nullable person field.");
            }
            Veterinarian veterinarianOrphanCheck = person.getVeterinarian();
            if (veterinarianOrphanCheck != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Person (" + person + ") cannot be destroyed since the Veterinarian " + veterinarianOrphanCheck + " in its veterinarian field has a non-nullable person field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(person);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Person> findPersonEntities() {
        return findPersonEntities(true, -1, -1);
    }

    public List<Person> findPersonEntities(int maxResults, int firstResult) {
        return findPersonEntities(false, maxResults, firstResult);
    }

    private List<Person> findPersonEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Person.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Person findPerson(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Person.class, id);
        } finally {
            em.close();
        }
    }

    public int getPersonCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Person> rt = cq.from(Person.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
